package cn.itcast.service.impl;

import cn.itcast.mapper.ClazzMapper;
import cn.itcast.mapper.StudentMapper;
import cn.itcast.pojo.Clazz;
import cn.itcast.pojo.PageResult;
import cn.itcast.pojo.Result;
import cn.itcast.pojo.Student;
import cn.itcast.service.StudentService;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.function.Function;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private ClazzMapper clazzMapper;

    //4.1学员列表查询
    @Override
    public Result search(String name, Integer degree, Integer clazzId, Integer page, Integer pageSize) {
        Page<Student> student = Page.of(page, pageSize);
        LambdaQueryWrapper<Student> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.like((name != null && !name.isEmpty()), Student::getName, name)
                .eq(degree != null, Student::getDegree, degree)
                .eq(clazzId != null, Student::getClazzId, clazzId);
        Page<Student> studentPage = page(student, queryWrapper);
        long total = studentPage.getTotal();
        List<Student> students = studentPage.getRecords();
        List<Integer> clazzNameId = students.stream().map(Student::getClazzId).toList();
        //根据clazzNameId查出班级列表
        List<Clazz> clazzes = clazzMapper.selectByIds(clazzNameId);
        students.forEach(stu -> {
            clazzes.stream().filter(clazz -> clazz.getId().equals(stu.getClazzId()))
                    .findFirst().ifPresent(clazz -> stu.setClazzName(clazz.getName()));
        });

        return Result.success("分页查询成功", new PageResult<>(total, students));

//        //1.告诉分页助手,我要查询第几页,每页显示多少条数据
//        PageHelper.startPage(page, pageSize);
//        //2.调用mapper层,查询学生信息
//        List<Student> students = studentMapper.search(name, degree, clazzId);
//        //3.向下转型
//        Page<Student> p = (Page<Student>) students;
//
//        //4.拿到总数量和结果
//        long total = p.getTotal();
//        List<Student> list = p.getResult();
//        PageResult pageResult = new PageResult(total, list);
//
//        return Result.success("分页查询成功", pageResult);
    }

    @Override
    public Result deleteByIdsStudent(List<Integer> ids) {
        removeByIds(ids);
        /*Integer rows = studentMapper.deleteByIds(ids);

        return rows != 0 ? Result.success("删除成功") : Result.error("删除失败");*/
        return Result.success("删除成功");
    }

    @Override
    public Result insertStudent(Student student) {
        //1.补全添加时间和创建时间
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        //3.补全默认值
        student.setViolationCount((short) 0);
        student.setViolationScore((short) 0);
        save(student);
        /*//1.补全添加时间和创建时间
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        //3.补全默认值
        student.setViolationCount((short) 0);
        student.setViolationScore((short) 0);
        //2.调用Mapper层插入数据
        Integer rows = studentMapper.insertStudent(student);
        return rows != 0 ? Result.success("添加成功") : Result.error("添加失败");*/
        return Result.success("添加成功");
    }

    @Override
    public Result selectById(Integer id) {
        Optional<Student> optById = getOptById(id);
        Student student = optById.get();
        /*Student student = studentMapper.selectById(id);
       return student != null ? Result.success("查询成功", student) : Result.error("查询失败");*/
        return Result.success("查询成功", student);
    }

    @Override
    public Result updateStudent(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        updateById(student);
        return Result.success("修改成功");
        /*//1.设置更新时间
        student.setUpdateTime(LocalDateTime.now());
        //2.调用mapper层修改数据
        Integer rows = studentMapper.updateStudent(student);
        return rows != 0 ? Result.success("修改成功") : Result.error("修改失败");*/
    }

    @Override
    public Result violation(Integer id, Integer score) {

        //1.根据学生id查到学员的信息
        Student byId = getById(id);
        if (score == 0) {
            return Result.error("违纪分数不能为0");
        }
        Student student = new Student();
        BeanUtils.copyProperties(byId, student);
        if (score < 0) {
            student.setViolationScore((short) (byId.getViolationScore() + score));
        } else {
            student.setViolationScore((short) (byId.getViolationScore() + score));
            student.setViolationCount((short) (byId.getViolationCount() + 1));
        }
        updateById(student);

        return Result.success("违纪更新成功");

        /*if (score == 0) {
            return Result.error("违纪分数不能为0");
        }

        if (score < 0) {
            studentMapper.updateScore1(id, score);
        } else {

            studentMapper.updateScore(id, score);
        }

        return Result.success("违纪更新成功");*/
    }

/*    @Override
    public Result violation(Integer id, Integer score) {
        //1.根据查出学员的信息
        Student student = studentMapper.selectById(id);
        //2.设置更新时间
        student.setUpdateTime(LocalDateTime.now());
        //3.设置学生的违纪次数和违纪分数
        student.setViolationCount((short) (student.getViolationCount() + 1));
        student.setViolationScore((short) (student.getViolationScore() + score));
        //4.更新学员的违纪次数和违纪分数,调用Mapper更新方法
        Integer rows = studentMapper.updateStudent(student);
        return rows != 0 ? Result.success("违纪更新成功") : Result.error("违纪更新失败");
    }*/
}
